package com.ming.service.impl;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ming.dao.BookRepository;
import com.ming.domain.Book;
import com.ming.service.BookService;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookRepository bookRepository;

    @Override
    public Optional<Book> findOne(Integer id) {
        return bookRepository.findById(id);
    }

    @Override
    public List<Book> findAll() {
        return bookRepository.findAll();
    }

    @Override
    public Optional<Book> updatePurchaseDate(Integer id, LocalDate date) {
        
        Optional<Book> book = bookRepository.findById(id);
        book.ifPresent(data -> {
            if (!date.equals(data.getPurchaseDate())) {
                data.setPurchaseDate(date);
                bookRepository.saveAndFlush(data);
            }
            
        });
        return book;
    }

    @Override
    public List<Book> findAllByDate(LocalDate date) {
        Specification<Book> spec = new Specification<Book>() {

            @Override
            public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                      
                List<Predicate> predicates = new ArrayList<>();
                
                Predicate predicate = criteriaBuilder.equal(root.get(Book._PURCHASE_DATE), date);
                
                predicates.add(predicate);

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            
                        
            }
            
        };

        return bookRepository.findAll(spec);
    }

    
}
